<template>
  <div>
    <img
      :src="pic.replace(/public/, $baseURL)"
      alt=""
      style="border-radius: 50%; width: 50px; height: 50px; margin-right: 10px"
      @click="uploadAction"
    />
    <input type="file" class="input-file" ref="upload" @change="startUpload" />
  </div>
</template>

<script>
import axios from "axios";
import { mapState, mapMutations } from "vuex";

export default {
  name: "uploadAvatar",
  components: {},
  data() {
    return {
      pic: window.sessionStorage.getItem("avatar"),
    };
  },
  watch: {
    avatar() {
      this.pic = window.sessionStorage.getItem("avatar");
    },
  },
  computed: {
    ...mapState(["avatar"]),
  },
  created() {},
  mounted() {},
  methods: {
    ...mapMutations(["changeAvatar"]),
    uploadAction() {
      if (this.pic) {
        this.$refs.upload.click();
      }
    },
    startUpload() {
      console.log(this.$refs.upload.files);

      const file = this.$refs.upload.files[0];
      console.log(file);
      var data = new FormData();
      data.append("avatar", file); // 上传文件需要表单对象， js 实例化一个表单对象
      data.append("phone", window.sessionStorage.getItem("telephone")); // 上传文件需要表单对象， js 实例化一个表单对象
      data.append("username", window.sessionStorage.getItem("username")); // 上传文件需要表单对象， js 实例化一个表单对象
      console.log(data);
      axios.post(`${this.$server}/sendavatar`, data).then((res) => {
        console.log(res, "上传头像响应");
        if (res.data.code == 200) {
          window.sessionStorage.setItem("avatar", res.data.avatar);
          this.$message.success("上传头像成功");
          this.changeAvatar(res.data.avatar);
          // location.reload();
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
img {
  cursor: pointer;
}

.input-file {
  display: none;
}
</style>
